package com.temp.realm;

import com.temp.entity.User;
import com.temp.service.RoleService;
import com.temp.service.UserService;
import com.temp.vo.UserRolePermissionVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<UserRolePermissionVO> userRolesAndPermissions = roleService.findUserRolesAndPermissions(user.getId());
        Set<String> permissions = userRolesAndPermissions.stream().map(UserRolePermissionVO::getPermName).collect(Collectors.toSet());
        Set<String> RoleNames = userRolesAndPermissions.stream().map(UserRolePermissionVO::getRoleName).collect(Collectors.toSet());
        log.info("{}用户具有的角色{}权限有{}",user,RoleNames,permissions);
        authorizationInfo.setRoles(RoleNames);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.findByEmail(token.getUsername());
        if (user == null) {
            throw new UnknownAccountException("apiMsg.userNotExist");
        }
        return new SimpleAuthenticationInfo(user, user.getPasswordHash(), ByteSource.Util.bytes(user.getSalt()), getName());
    }
}
